/* Prepare inputs for demographics at the market level; also create market-category effects   */
********** Demographics at the market level
clear all
set more off
cd ""  //targed directory


clear
use "./prepare/allbasic.dta",clear
keep if year==2006
keep id hsa
tempfile ahaid_hsa
save `ahaid_hsa'



clear 
insheet using "./rawdata/hsa.csv",clear
tempfile hsa_fips
save `hsa_fips'



clear
use "./rawdata/population demographics 1990_2012.dta", clear
keep fips year popest_tot popest_age65plus
drop if year<1997|year>2011
tempfile pop
save `pop'



clear
use "./rawdata/AHRF county controls 1975_2013.dta", clear
keep FIPS Year IncPC
rename (FIPS Year IncPC) (fips year pcinc)
drop if year<1997|year>2011
merge 1:1 fips year using `pop'
keep if _merge==3
drop _merge
gen incpop=pcinc*popest_tot
merge m:1 fips using `hsa_fips'
keep if _merge==3
drop _merge

bys hsa year:egen totpop=total(popest_tot)
bys hsa year:egen totpop65=total(popest_age65plus)

bys hsa year:egen totincpop=total(incpop)
gen tmp_popest_tot=popest_tot
replace tmp_popest_tot=. if pcinc==.
bys hsa year:egen tot_tmp_popest_tot=total(tmp_popest_tot)
gen avginc=totincpop/tot_tmp_popest_tot


duplicates drop hsa year,force
keep hsa year totpop totpop65 avginc



foreach YEAR of num 2006/2010 {
preserve
keep if year==`YEAR'
merge 1:m hsa using `ahaid_hsa'
keep if _merge==3
drop _merge
tempfile pop`YEAR'
save `pop`YEAR''
restore
}


clear
use `pop2006',clear
append using `pop2007'
append using `pop2008'
append using `pop2009'
append using `pop2010'


save "./prepare/demographic4mkt",replace






**********
**********
********** Market-category effects
clear all
set more off
set matsize 10000


*** Demographics: population and income per capita
clear
use "./prepare/demographic4mkt"
duplicates drop hsa year,force
keep hsa year totpop totpop65 avginc
gen perc65=totpop65/totpop
replace totpop=log(totpop)
replace totpop65=log(totpop65)
replace avginc=log(avginc)
tempfile pop
save `pop'
***



clear
use "./prepare/allbasic.dta",clear


*** Create HHI
preserve
keep id year admtot hsa
bys hsa year:egen totadm_mkt=total(admtot)
gen admsh=admtot/totadm_mkt
bys hsa year:egen hhi=total(admsh^2)
duplicates drop hsa year,force
keep hsa year hhi
tempfile hhi
save `hhi'
restore
***



*** Merge other demographics at the market level
merge m:1 hsa year using `pop'
keep if _merge==3
drop _merge


merge m:1 hsa year using `hhi'
keep if _merge==3
drop _merge



*** Create DV in the regression of estimating market-category effects:
gen const=1
bys hsa year:egen totadp=total(adj_vnd>1)
bys hsa year:egen nhosp=total(const)

duplicates drop hsa year,force
gen adpratio=totadp/nhosp

duplicates drop hsa year,force
xi:reg adpratio hhi totpop65 i.year i.hsa,nocon vce(cluster hsa)
est sto comb
esttab comb using "./prepare/mktFEs_comb1.csv",replace nose not wide plain noobs nodep nonum

















